package com.tedu.udm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tedu.udm.ex.ServiceException;
import com.tedu.udm.mapper.*;
import com.tedu.udm.pojo.dto.TeamAddNewDTO;
import com.tedu.udm.pojo.dto.TeamUpdateDTO;
import com.tedu.udm.pojo.entity.*;
import com.tedu.udm.pojo.vo.TeamListItemVO;
import com.tedu.udm.pojo.vo.TeamStandardVO;
import com.tedu.udm.service.ITeamService;
import com.tedu.udm.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 处理小组数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class TeamServiceImpl implements ITeamService {
    @Autowired
    private TeamMapper teamMapper;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClassTeamMapper classTeamMapper;
    @Autowired
    private UserTeamMapper userTeamMapper;

    public TeamServiceImpl() {
        log.debug("创建业务对象：TeamServiceImpl");
    }

    @Override
    public void addNew(Long classId,TeamAddNewDTO teamAddNewDTO) {
        log.debug("开始处理【添加小组】的业务，参数：{}", teamAddNewDTO);

        {
            log.debug("检查班级id是否存在班级！");
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("id",classId);
            Classes classes = classMapper.selectById(classId);
            if (classes == null) {
                String message = "添加小组失败，班级名id信息错误，请重试！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        {
            log.debug("检查小组组长是否存在数据！");
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("id", teamAddNewDTO.getSupervisorId());
            int count = userMapper.selectCount(wrapper);
            if (count < 1) {
                String message = "删除小组失败，小组组长信息不存在！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        {
            log.debug("检查同班级的小组名称是否重复！");
            String teamName = teamAddNewDTO.getTeamName();
            TeamStandardVO team = teamMapper.selectByClassIdAndTeamName(classId,teamName);
            if (team != null) {
                String message = "添加班级失败，小组名【" + teamName + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        log.debug("检查通过，准备插入小组信息！");
        Team team = new Team();
        // 通过BeanUtils.copyProperties()方法将参数对象的各属性值复制到Admin对象中
        BeanUtils.copyProperties(teamAddNewDTO, team);
        int rows = teamMapper.insert(team);
        if (rows != 1) {
            String message = "添加班级失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        log.debug("插入小组信息完成，准备插入班级与小组的关系数据！");
        ClassTeam classTeam = new ClassTeam();
        classTeam.setClassId(classId);
        classTeam.setTeamId(team.getId());
        rows = classTeamMapper.insert(classTeam);
        if (rows != 1) {
            String message = "添加小组失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        log.debug("插入小组信息完成，准备将组长加入到小组成员中！");
        UserTeam userTeam = new UserTeam();
        userTeam.setTeamId(team.getId());
        userTeam.setUserId(team.getSupervisorId());
        rows = userTeamMapper.insert(userTeam);
        if (rows != 1) {
            String message = "添加小组失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void delete(Long teamId) {
        log.debug("开始处理【删除小组】的业务，参数：{}", teamId);

        {
            log.debug("检查小组是否存在成员数据！");
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("team_id",teamId);
            int count = userTeamMapper.selectCount(wrapper);
            if (count != 0) {
                String message = "删除小组失败，请先删除组员关系！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        log.debug("检查通过，准备删除小组信息！");
        int rows = teamMapper.deleteById(teamId);
        if (rows != 1) {
            String message = "删除小组失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

        {
            log.debug("删除小组信息完成，准备删除班级关联信息！");
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("team_id",teamId);
            rows = classTeamMapper.delete(wrapper);
            if (rows < 1) {
                String message = "删除小组失败，服务器忙，请稍后再次尝试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_DELETE, message);
            }
        }
    }

    @Override
    public void update(TeamUpdateDTO teamUpdateDTO) {
        log.debug("开始处理【修改小组】的业务，参数：{}", teamUpdateDTO);

        {
            log.debug("检查小组组长是否存在数据！");
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("id", teamUpdateDTO.getSupervisorId());
            int count = userMapper.selectCount(wrapper);
            if (count < 1) {
                String message = "删除小组失败，小组组长信息不存在！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        log.debug("获取小组所属班级的id！");
        Long classId;
        {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("team_id",teamUpdateDTO.getId());
            ClassTeam classTeam = classTeamMapper.selectOne(wrapper);
            if (classTeam == null) {
                String message = "修改小组信息失败，班级信息查询错误！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
            classId = classTeam.getClassId();
        }
        {
            log.debug("检查同班级的小组名称是否重复！");
            String teamName = teamUpdateDTO.getTeamName();
            TeamStandardVO team = teamMapper.selectByClassIdAndTeamNameAndTeamId(classId,teamName,teamUpdateDTO.getId());
            if (team != null) {
                String message = "修改小组失败，小组名【" + teamName + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        log.debug("检查通过，准备修改小组信息！");
        Team team = new Team();
        // 通过BeanUtils.copyProperties()方法将参数对象的各属性值复制到Admin对象中
        BeanUtils.copyProperties(teamUpdateDTO, team);
        int rows = teamMapper.updateById(team);
        if (rows != 1) {
            String message = "修改小组失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }

        log.debug("修改小组信息完成，检查新组长是否是小组成员");
        {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("user_id",teamUpdateDTO.getSupervisorId());
            wrapper.eq("team_id",teamUpdateDTO.getId());
            UserTeam u = userTeamMapper.selectOne(wrapper);
            if (u!=null) {
                return;
            }
        }

        log.debug("不是小组成员，准备插入新组长与小组的关系数据！");
        UserTeam userTeam = new UserTeam();
        userTeam.setTeamId(teamUpdateDTO.getId());
        userTeam.setUserId(teamUpdateDTO.getSupervisorId());
        rows = userTeamMapper.insert(userTeam);
        if (rows != 1) {
            String message = "添加小组失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public TeamStandardVO get(Long id) {
        log.debug("开始处理【小组详情】的业务，无参数！");
        Team team = teamMapper.selectById(id);
        TeamStandardVO teamStandardVO = new TeamStandardVO();
        BeanUtils.copyProperties(team,teamStandardVO);
        return teamStandardVO;
    }

    @Override
    public List<TeamListItemVO> list() {
        log.debug("开始处理【小组列表】的业务，无参数！");
        List<Team> list = teamMapper.selectList(null);
        List<TeamListItemVO> lists = new ArrayList<>();
        for (Team team:list) {
            TeamListItemVO teamListItemVO = new TeamListItemVO();
            BeanUtils.copyProperties(team,teamListItemVO);
            lists.add(teamListItemVO);
        }
        return lists;
    }

    @Override
    public List<TeamListItemVO> listByClassId(Long classId) {
        log.debug("开始处理【小组列表】的业务，无参数！");
        List<TeamListItemVO> list = teamMapper.selectByClassId(classId);
        return list;
    }
}
